$(function () {
	var bg = chrome.extension.getBackgroundPage();
	G = bg.SINA;
	var longSetting = JSON.parse(G.get("longSetting"));
	$('body').prepend(bg['fullHtml']).css(JSON.parse(localStorage.getItem('sina_ked_bodyCss'))).css("background-image",localStorage.getItem('sina_ked_backgroundImage'));
	
	var canvas = document.createElement("canvas");
	var clientHeight,scrollHeight;
	
	if(longSetting.sy){
		var img = new Image();
		img.onload = function(){
			$("#sy").append(img).show();
		}
		img.src = longSetting.sy;
	}
	
	$("#sendBtn").click(function () {
		window.location.href = window.location.href+"?reload=true";
	});
	var readyState;
	var scolled = false;
	var lastHeigt;
	function captureAndScroll(y) {
		if(y==0){
			clientHeight = document.documentElement.clientHeight;
			scrollHeight = document.body.scrollHeight;
			readyState = (scrollHeight == clientHeight);
			canvas.height = scrollHeight;
			canvas.width = document.body.scrollWidth;
		}
		chrome.tabs.captureVisibleTab(null, {
			format : 'png'
		}, function (data) {
			var image = new Image();
			image.onload = function () {
				var context = canvas.getContext('2d');
				if (readyState && scolled) {
					context.drawImage(image, 0, (clientHeight-lastHeigt), image.width, lastHeigt,0,y,image.width, lastHeigt);
				} else {
					context.drawImage(image, 0, y, image.width, image.height);
				}
				if (readyState) {
					bg['previewImg'] = canvas.toDataURL("image/png");
					window.open(chrome.extension.getURL('/ked/previewImg.html'),"preview");
					return;
				}
				document.body.scrollTop = y + clientHeight;
				if (document.body.scrollTop != (y + clientHeight)) {
					lastHeigt = document.body.scrollTop - y;
					readyState = true;
					scolled = true;
				}

				setTimeout(function () {
					captureAndScroll(y + clientHeight);
				}, 500);
			}
			image.src = data;
		});
	}
	
	if(window.location.href.split("?").length > 1){
		prettyPrint();
		$('.toolbar').hide();
		document.body.scrollTop = 0;
		setTimeout(function () {
			captureAndScroll(0);
		}, 500);
	}else{
		setTimeout(function(){
			if(document.documentElement.clientWidth <  document.body.scrollWidth){
				window.resizeTo(document.body.scrollWidth + 50);
				setTimeout(function(){
					window.location.reload();
				},200);
			}
			prettyPrint();
			var Timer;
			window.onresize = function(){
				if(Timer){
					clearTimeout(Timer);
				}
				Timer = setTimeout(function(){
					if(document.documentElement.clientWidth <  document.body.scrollWidth){
						window.resizeTo(document.body.scrollWidth + 70);
					}
				},100);
			}
		},100);
	}
});
